package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService   {

    @Override
    public void updateMoney(Long id, Integer money) {
        User user = getById(id);
        if (user==null||user.getStatus()!=1){
            throw new RuntimeException("该用户状态不正常");
        }
        if (user.getBalance()<money){
            throw new RuntimeException("余额不足");
        }
//        LambdaQueryWrapper<User> wrapper =new LambdaQueryWrapper<>();
//        wrapper.eq(User::getId,id);
//        baseMapper.updateMoney(wrapper,money);
        //复杂更新
        int remainBalance = user.getBalance()-money;
        lambdaUpdate()
                .set(User::getBalance,remainBalance)
                .set(remainBalance==0,User::getStatus,2)
                .eq(User::getId,id)
                .eq(User::getBalance,user.getBalance()) //乐观锁
                .update();

    }

    @Override
    public List<User> selectList(UserQuery userQuery) {
        List<User> list = lambdaQuery().like(userQuery.getName() != null, User::getUsername, userQuery.getName())
                .eq(userQuery.getStatus() != null, User::getStatus, userQuery.getStatus())
                .ge(userQuery.getMinBalance() != null, User::getBalance, userQuery.getMinBalance())
                .le(userQuery.getMaxBalance() != null, User::getBalance, userQuery.getMaxBalance())
                .list();
        return list;
    }

    @Override
    public UserVO selectUserAndAddresses(Long id) {
        User user = getById(id);
        if (user==null||user.getStatus()==2){
            throw new RuntimeException("用户不存在");
        }
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        if (CollUtil.isNotEmpty(addresses)){
            userVO.setAddresses( BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> selectListAndAddresses(List<Long> ids) {
        //获取所有用户
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)){
            return Collections.emptyList();
        }
        //获取地址
        List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId,ids).list();
        //转换AddressVO
        List<AddressVO> addressVOList = BeanUtil.copyToList(addresses, AddressVO.class);
        //用户地址分组
        Map<Long,List<AddressVO>>addressMap=new HashMap<>(0);
        if (CollUtil.isNotEmpty(addressVOList)){
            addressMap=addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }
        //类型转换
        List<UserVO>list=new ArrayList<>(users.size());
        for (User user : users) {
            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
            list.add(vo);
            //转换地址
            vo.setAddresses(addressMap.get(user.getId())); //指向同一个对象,放前后都一样
        }
        return list;
    }

    @Override
    public PageDTO<UserVO> queryUserPage(UserQuery userQuery) {
        return null;
    }
}
